package com.pm.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.pm.common.config.ParamConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;

@Slf4j
@Component
public class OaVliTokenUtils {//验证oa单点登录令牌工具类

    @Resource
    private ParamConfig paramConfig;

    @Resource
    private RestTemplate restTemplate;

    public String vliTicket(String ticket){
        try {
//            MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
//            params.add("tokenString",ticket);
//            HttpHeaders headers = new HttpHeaders();
//            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//            HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
//            JSONObject response = restTemplate.postForObject(paramConfig.getOaValidate(), requestEntity, JSONObject.class);

            String url = paramConfig.getOaAddr()+"/api/pro-sso/proSsoRestService/validate";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf(MediaType.MULTIPART_FORM_DATA_VALUE));
            MultiValueMap<String, Object> formData = new LinkedMultiValueMap<>();
            formData.put("tokenString", Collections.singletonList(ticket));
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(formData, headers);
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);
            JSONObject response = JSONObject.parseObject(responseEntity.getBody());


            if(response.getBoolean("success")){
                JSONObject userInfo = response.getJSONObject("userInfo");
                return userInfo.getString("userNo");//获取工号
            }else {
                log.error("oa单点登录验证token失败："+response);
                return "";
            }
        } catch (RestClientException e) {
            e.printStackTrace();
            log.error("oa单点登录验证token异常："+e);
            return "";
        }
    }
}
